'use strict';

exports.main = async (event, context) => {
  console.log('=== markAllMessagesRead 云函数开始 ===')
  console.log('1. 接收参数:', event)
  
  const db = uniCloud.database();
  const { userId, messageType } = event;

  if (!userId) {
    console.log('❌ 缺少必要参数:', { userId })
    return {
      code: 400,
      msg: '缺少必要参数'
    };
  }

  try {
    console.log('2. 批量标记消息为已读，类型:', messageType)
    console.log('2.1 用户ID:', userId)
    
    let result = { updated: 0 };
    
    // 根据消息类型批量标记已读
    if (!messageType || messageType === 'interaction') {
      // 标记互动消息为已读
      console.log('3. 开始标记互动消息为已读...')
      
      const interactionResult = await db.collection('interaction-messages')
        .where({
          receiver_id: userId,
          is_read: false
        })
        .update({
          is_read: true,
          read_time: new Date()
        });
      
      result.updated += interactionResult.updated;
      console.log('3.1 互动消息已读更新:', interactionResult.updated)
    }
    
    if (!messageType || messageType === 'private') {
      // 标记私信消息为已读
      console.log('3.1 开始标记私信消息为已读...')
      
      // 先查询未读消息
      const unreadMessages = await db.collection('chatMessages')
        .where({
          receiverId: userId,
          status: { $ne: 'read' }
        })
        .get();
      
      console.log('3.2 找到未读私信消息数量:', unreadMessages.data.length)
      
      if (unreadMessages.data.length > 0) {
        const chatResult = await db.collection('chatMessages')
          .where({
            receiverId: userId,
            status: { $ne: 'read' }
          })
          .update({
            status: 'read',
            readTime: new Date()
          });
        
        result.updated += chatResult.updated;
        console.log('3.3 私信消息已读更新:', chatResult.updated)
      } else {
        console.log('3.3 没有未读私信消息')
      }
    }
    
    if (!messageType || messageType === 'notification') {
      // 标记通知消息为已读
      console.log('4. 开始标记通知消息为已读...')
      
      const notificationResult = await db.collection('notification-messages')
        .where({
          user_id: userId,
          is_read: false
        })
        .update({
          is_read: true,
          read_time: new Date()
        });
      
      result.updated += notificationResult.updated;
      console.log('4.1 通知消息已读更新:', notificationResult.updated)
    }
    
    if (!messageType || messageType === 'recommend') {
      // 标记推荐消息为已读
      console.log('5. 开始标记推荐消息为已读...')
      
      const recommendResult = await db.collection('recommendMessages')
        .where({
          user_id: userId,
          is_read: false
        })
        .update({
          is_read: true,
          read_time: new Date()
        });
      
      result.updated += recommendResult.updated;
      console.log('5.1 推荐消息已读更新:', recommendResult.updated)
    }
    
    console.log('✅ 批量标记已读完成，共更新', result.updated, '条消息')

    return {
      code: 200,
      msg: '批量标记已读成功',
      data: { 
        updatedCount: result.updated,
        messageType: messageType || 'all'
      }
    };
  } catch (error) {
    console.error('❌ 批量标记已读失败:', error);
    return {
      code: 500,
      msg: '批量标记已读失败',
      error: error.message
    };
  }
};